package com.api.qfengx.data.res;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;
import com.weaver.qfengx.*;
import com.weaver.qfengx.config.DevModeConfig;
import com.weaver.qfengx.entity.Result;
import weaver.file.ImageFileManager;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 资源下载servlet
 * @Author Opp <qffg1998@126.com>
 * @Date 2023-03-05 00:50
 */
@WebServlet("/resource/qfengx/query")
public class ResourceServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Map<String, Object> paramsMap = RequestUtils.getParamsMap(request);
            String id = StringUtils.val(paramsMap.get("id"));
            String token = StringUtils.val(paramsMap.get("token"), "default");
            if (StrUtil.isBlank(id)) {
                ResponseUtils.respToJson(Result.paramErr(), response);
                return;
            }
            String value = DevModeConfig.getPropConfig("resource.query." + token, "").getValue();
            if (StrUtil.isBlank(value)) {
                ResponseUtils.respToJson(Result.fail("资源未配置"), response);
                return;
            }
            List<String> cateList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value);
            String cateId = DocUtils.getSeccategory(id);
            if (!cateList.contains(cateId)) {
                ResponseUtils.respToJson(Result.fail("资源未授权"), response);
                return;
            }
            ImageFileManager imageFileManager = ImageFileUtils.imageFileManager(id);
            boolean transfer = HttpServletUtils.transfer(imageFileManager.getImageFileName(), imageFileManager.getInputStream(), request, response);
            if (!transfer) {
                ResponseUtils.respToJson(Result.fail("资源传输失败"), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtils.respToJson(Result.exception(e.getMessage()), response);
        }
    }

}
